package core

import (
	"context"
	"errors"
	"fmt"
	"github.com/redis/go-redis/v9"
	"xinduobang/stock/common"
	"xinduobang/stock/core/log"
)

var (
	ctx          = context.Background()
	redisFactory *redis.Client
	RedisNilErr  = errors.New("redis: nil")
)

func InitRedisForTest(redisConfig *common.RedisConfig) (err error) {
	return initRedis(redisConfig)
}

func initRedis(redisConfig *common.RedisConfig) (err error) {
	addr := fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port)
	redisFactory = redis.NewClient(&redis.Options{
		Addr:         addr,
		Password:     redisConfig.Password, // no password set
		DB:           redisConfig.Db,
		PoolFIFO:     true,
		PoolSize:     redisConfig.PoolSize,     // 连接池大小
		MinIdleConns: redisConfig.MinIdleConns, // 最小空闲连接数
		MaxIdleConns: redisConfig.MaxIdleConns, // 最大空闲连接数
	})

	_, err = redisFactory.Ping(ctx).Result()
	if err != nil {
		log.Errorf("redis init error:%v", err)
		return
	}
	log.Infof("Connected to Redis %v!", addr)
	return
}

func GetRedis() (*redis.Client, error) {
	if redisFactory == nil {
		return nil, fmt.Errorf("redisFactory is nil")
	}

	return redisFactory, nil
}

func CloseRedis() {
	log.Info("redis close ...")
	err := redisFactory.Close()
	if err != nil {
		log.Errorf("redis close error:%v", err)
		return
	}
}
